<?php

/**
 * Logger
 * @author LiangZhixian
 */
require_once("LoggerConfig.php");

class Logger {
	
	var $logDebug = false;
	var $logWarn  = false;
	var $logInfo  = false;
	var $logError = false;
	var $logFatal = false;
	
	var $logToFile = false;
	var $logToScreen = false;
	
	var $file;
	
	static $instance;
			
	private function Logger()
	{			
		if (defined('LOG_DEBUG_'))
		    $this->logDebug = LOG_DEBUG_;
		if (defined('LOG_WARN_'))
			$this->logWarn = LOG_WARN_;
	    if (defined('LOG_INFO_'))
			$this->logInfo = LOG_INFO_;
		if (defined('LOG_ERROR_'))
			$this->logError = LOG_ERROR_;
		if (defined('LOG_FATAL_'))
			$this->logFatal = LOG_FATAL_;			
		if (defined('LOG_TO_FILE_'))
		    $this->logToFile = LOG_TO_FILE_;
		if (defined('LOG_TO_SCREEN_'))
		    $this->logToScreen = LOG_TO_SCREEN_;
			
		if ($this->logToFile)
		{
			$this->file = fopen(LOG_FILE,'a+');
		}	

	}
	
	function __destruct()
	{		
		if ($this->logToFile)
		{
			fclose($this->file);
		}
	}
	
	static function &getLogger()
	{		
		if (!isset(self::$instance))
		{
			self::$instance = new Logger();			
		}				
				
		return self::$instance;		
	}
	    
	private function callstackmsg()
	{
		$trace = debug_backtrace();
		
		$stack = $trace[1];		
	
		$file = isset($stack['file'])?$stack['file']:'';
		$line = isset($stack['line'])?$stack['line']:'';
	//	$func = isset($stack['function'])?$stack['function']:'';
	//	$args = isset($stack['args'])?$stack['args']:'';
	//	$class = isset($stack['class'])?$stack['class']:'';
		
				
		return $file.":".$line;
		
	}
	
	private function log($m)
	{
		$l = date("Y-m-d H:i:s").$m;
		//$l = $m;
		if ($this->logToFile)
		{
			fwrite($this->file,$l,strlen($l)); 
		}
		
		if ($this->logToScreen)
		{
			echo $l;
		}
	}
	
	function debug($msg)
	{
		if ($this->logDebug)
		{
			$line = $this->callstackmsg();
			$this->log("-DEBUG (".$line.") - ".strval($msg)."\r\n");		
		}
	}
	
	function warn($msg)
	{
		if ($this->logWarn)
		{
			$line = $this->callstackmsg();
			$this->log("-WARN (".$line.") - ".strval($msg)."\r\n");		
		}
	}
	
	function info($msg)
	{
		if ($this->logInfo)
		{
			$line = $this->callstackmsg();
			$this->log("-INFO (".$line.") - ".strval($msg)."\r\n");		
		}
	}
	
	function error($msg)
	{
		if ($this->logError)
		{
			$line = $this->callstackmsg();
			$this->log("-ERROR (".$line.") - ".strval($msg)."\r\n");	
		}
	}
	
	function fatal($msg)
	{
		if ($this->logFatal)
		{
			$line = $this->callstackmsg();
			$this->log("-FATAL (".$line.") - ".strval($msg)."\r\n");	
		}
	}
}

?>